package com.ruoyi.xqsp.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateTime;
import com.ruoyi.xqsp.constant.ImgUrl;
import com.ruoyi.xqsp.domain.entity.ChatHistory;
import com.ruoyi.xqsp.service.ISpUsersService;
import org.apache.xmlbeans.impl.xb.xsdschema.BlockSet;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.xqsp.domain.SpChat;
import com.ruoyi.xqsp.service.ISpChatService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 聊天信息Controller
 *
 * @author ruoyi
 * @date 2021-05-10
 */
@RestController
@RequestMapping("/xqsp/chat")
public class SpChatController extends BaseController {
    @Autowired
    private ISpChatService spChatService;
    @Autowired
    private ISpUsersService spUsersService;

    /**
     * 查询聊天信息列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:list')")
    @GetMapping("/list")
    public TableDataInfo list(SpChat spChat) {
        startPage();
        List<SpChat> list = spChatService.selectSpChatList(spChat);
        SpChat spChat1;
        List<SpChat> spChatList = new ArrayList<>();
        for (SpChat chat : list) {
            spChat1 = new SpChat();
            spChat1 = chat;
            if (chat.getUserId() == 1) {
                spChat1.setUserName(spUsersService.selectSpUsersById(chat.getServiceId()).getUserPhone());
            } else {
                spChat1.setUserName(spUsersService.selectSpUsersById(chat.getUserId()).getUserPhone());
            }
            spChatList.add(spChat1);
        }
        return getDataTable(spChatList);
    }

    /**
     * 查询聊天信息列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:list')")
    @GetMapping("/list1")
    public TableDataInfo list1(SpChat spChat) {
        startPage();
        List<SpChat> list = spChatService.selectSpChatList1(spChat);
        SpChat spChat1;
        List<SpChat> spChatList = new ArrayList<>();
        for (SpChat chat : list) {
            spChat1 = new SpChat();
            spChat1 = chat;
            spChat1.setUserName(spUsersService.selectSpUsersById(chat.getUserId()).getUserPhone());
            spChatList.add(spChat1);
        }
        return getDataTable(spChatList);
    }

    /**
     * 查询聊天信息列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:list')")
    @GetMapping("/list2")
    public TableDataInfo list2(SpChat spChat) {

        List<SpChat> list = spChatService.selectSpChatList2(spChat);
        SpChat spChat1;
        List<SpChat> spChatList = new ArrayList<>();
        for (SpChat chat : list) {
            spChat1 = new SpChat();
            spChat1 = chat;
            if (chat.getUserId() == 1) {
                spChat1.setUserName(spUsersService.selectSpUsersById(chat.getServiceId()).getUserPhone());
            } else {
                spChat1.setUserName(spUsersService.selectSpUsersById(chat.getUserId()).getUserPhone());
            }

            spChatList.add(spChat1);
        }
        return getDataTable(spChatList);
    }

    /**
     * 导出聊天信息列表
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:export')")
    @Log(title = "聊天信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SpChat spChat) {
        List<SpChat> list = spChatService.selectSpChatList(spChat);
        ExcelUtil<SpChat> util = new ExcelUtil<SpChat>(SpChat.class);
        return util.exportExcel(list, "chat");
    }

    /**
     * 获取聊天信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:query')")
    @GetMapping(value = "/{chatId}")
    public AjaxResult getInfo(@PathVariable("chatId") Long chatId) {
        return AjaxResult.success(spChatService.selectSpChatById(chatId));
    }

    /**
     * 新增聊天信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:add')")
    @Log(title = "聊天信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpChat spChat) {

        if (spChat.getChatContent().indexOf("http://localhost:8080")!=-1){
            String img=spChat.getChatContent().replace("http://localhost:8080",ImgUrl.url());
            spChat.setChatContent(img);
        }
        spChat.setChatTime(new Date());
        spChat.setUserId(1l);
        spChat.setChatState(0);
        spChatService.updateSpChatByUserId(spChat.getUserId());
        Long a = spChatService.selectSpChatByIds(spChat.getServiceId()).getChatNumber();
        spChat.setChatNumber(++a);
        return toAjax(spChatService.insertSpChat(spChat));
    }

    /**
     * 修改聊天信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:edit')")
    @Log(title = "聊天信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpChat spChat) {
        return toAjax(spChatService.updateSpChat(spChat));
    }

    /**
     * 删除聊天信息
     */
    @PreAuthorize("@ss.hasPermi('xqsp:chat:remove')")
    @Log(title = "聊天信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{chatIds}")
    public AjaxResult remove(@PathVariable Long[] chatIds) {
        return toAjax(spChatService.deleteSpChatByIds(chatIds));
    }

    /**
     * 根据发送人和接收人id查询
     *
     * @param spChat
     * @return
     */
    @PostMapping("/getAll")
    public TableDataInfo getAll(@RequestBody SpChat spChat) {


        List<SpChat> list = spChatService.selectSpChatLists(spChat.getUserId(), spChat.getServiceId());
        List<SpChat> objects = new ArrayList<>();
        TableDataInfo dataTable = getDataTable(list);
        List<SpChat> rows = (List<SpChat>) dataTable.getRows();

        if (rows.size() - 1 > 20) {
            for (int i = 19; i >= 0; i--) {
                objects.add(rows.get(i));
            }
        } else {
            for (int i = rows.size() - 1; i >= 0; i--) {
                objects.add(rows.get(i));
            }
        }

        dataTable.setRows(objects);
        return dataTable;
    }


    /**
     * xia拉
     *
     * @return
     */
    @PostMapping("/getAllUp")
    public TableDataInfo getAllUp(@RequestBody ChatHistory chatHistory) {
        Long a = spChatService.selectSpChatByIds(chatHistory.getUserId()).getChatNumber();
        List<SpChat> objects = new ArrayList<>();
        List<SpChat> object = new ArrayList<>();
        List<SpChat> list = new ArrayList<>();
        //SpChat spChat;
        List<SpChat> spChatList = spChatService.selectSpChatList3(chatHistory.getUserId());

        for (SpChat chat : spChatList) {
            if (chat.getChatNumber() < chatHistory.getChatNumber()) {
                list.add(chat);
            }
        }

        if (list.size() > 20) {
            for (int i = 0; i < 20; i++) {
                objects.add(list.get(i));
            }

            for (int i = objects.size() - 1; i >= 0; i--) {
                object.add(objects.get(i));
            }
            return getDataTable(object);
        } else {
            for (int i = 0; i < list.size(); i++) {
                objects.add(list.get(i));
            }
            for (int i = objects.size() - 1; i >= 0; i--) {
                object.add(objects.get(i));
            }
            return getDataTable(object);
        }


//
//        if (chatHistory.getChatNumber()>1){
//            if (a-chatHistory.getChatNumber()>=20){
//
//                for (Long i=chatHistory.getChatNumber();i<=chatHistory.getChatNumber()+20;i++){
//                    spChat=new SpChat();
//                    spChat=spChatService.selectSpChatByIdAndNumber(chatHistory.getUserId(),i);
//                    list.add(spChat);
//                }
//                for (int i= list.size()-1; i >=0; i--) {
//                    objects.add(list.get(i));
//                }
//                return getDataTable(objects);
//            }else {
//                for (Long i=chatHistory.getChatNumber();i<=a;i++){
//                    spChat=new SpChat();
//                    spChat=spChatService.selectSpChatByIdAndNumber(chatHistory.getUserId(),i);
//                    list.add(spChat);
//                }
//                for (int i= list.size()-1; i >=0; i--) {
//                    objects.add(list.get(i));
//                }
//                return getDataTable(objects);
//            }
//        }else {
//            return getDataTables();
//        }


    }

    /**
     * 上拉
     *
     * @param chatHistory
     * @return
     */
    @PostMapping("/getAllDown")
    public TableDataInfo getAllDown(@RequestBody ChatHistory chatHistory) {

        List<SpChat> objects = new ArrayList<>();
        List<SpChat> object = new ArrayList<>();
        Long a = spChatService.selectSpChatByIds(chatHistory.getUserId()).getChatNumber();
        List<SpChat> list = new ArrayList<>();

        List<SpChat> spChatList = spChatService.selectSpChatList3(chatHistory.getUserId());

        for (SpChat chat : spChatList) {
            if (chat.getChatNumber() > chatHistory.getChatNumber()) {
                list.add(chat);
            }
        }
        if (list.size() > 20) {
            for (int i = 0; i < 20; i++) {
                objects.add(list.get(i));
            }
            for (int i = objects.size() - 1; i >= 0; i--) {
                object.add(objects.get(i));
            }
            return getDataTable(object);
        } else {
            for (int i = 0; i < list.size(); i++) {
                objects.add(list.get(i));
            }
            for (int i = objects.size() - 1; i >= 0; i--) {
                object.add(objects.get(i));
            }
            return getDataTable(object);
        }

//        SpChat spChat;
//        if (chatHistory.getChatNumber()<a){
//            if (a-chatHistory.getChatNumber()>=20){
//                Long b= chatHistory.getChatNumber()+20;
//                for (Long i=chatHistory.getChatNumber();i<=b;i++){
//                    spChat=new SpChat();
//                    spChat=spChatService.selectSpChatByIdAndNumber(chatHistory.getUserId(),i);
//                    list.add(spChat);
//                }
//                for (int i= list.size()-1; i >=0; i--) {
//                    objects.add(list.get(i));
//                }
//                return getDataTable(objects);
//            }else {
//                for (Long i=chatHistory.getChatNumber();i<=a;i++){
//                    spChat=new SpChat();
//                    spChat=spChatService.selectSpChatByIdAndNumber(chatHistory.getUserId(),i);
//                    list.add(spChat);
//                }
//                for (int i= list.size()-1; i >=0; i--) {
//                    objects.add(list.get(i));
//                }
//                return getDataTable(objects);
//            }
//        }else {
//            return getDataTables();
//        }

    }

    /**
     * 聊天
     *
     * @param spChat
     * @return
     */
    @PostMapping("/addChat")
    public AjaxResult addChat(@RequestBody SpChat spChat) {
        spChat.setChatTime(new Date());
        if (spChat.getChatContent().indexOf("http://localhost:8080")!=-1){
            String img=spChat.getChatContent().replace("http://localhost:8080",ImgUrl.url());
            spChat.setChatContent(img);
        }
        if (spChatService.selectSpChatByIds(spChat.getUserId())== null) {
            spChat.setChatNumber(0l);
        } else {
            Long a = spChatService.selectSpChatByIds(spChat.getUserId()).getChatNumber();
            spChat.setChatNumber(++a);
        }

        return toAjax(spChatService.insertSpChat(spChat));
    }

    /**
     * 定时删除，每天凌晨一点执行一次删除时间超七天的聊天记录
     */
    @Scheduled(cron = "0 0 1 * * ?  ")
    public void delChat() {
        SpChat spChat = new SpChat();
        List<SpChat> list = spChatService.selectSpChatList(spChat);
        DateTime dateTime = DateTime.now();
        Integer t = 1000 * 60 * 60 * 24;
        for (SpChat spChat1 : list) {
            long minus = ((dateTime.getTime() - spChat1.getChatTime().getTime()) / t);
            if (minus >= 7) {
                spChatService.deleteSpChatById(spChat1.getChatId());
            }
        }
    }

//
//    @GetMapping("/test")
//    public AjaxResult test(){
//        SpChat spChat=new SpChat();
//        List<SpChat>list=  spChatService.selectSpChatList(spChat);
//        DateTime dateTime=DateTime.now();
//        Integer t=1000*60*60*24;
//        for (SpChat spChat1:list){
//            long minus=((dateTime.getTime()-spChat1.getChatTime().getTime())/t);
//            System.out.println(minus);
//            if (minus>=7){
//                spChatService.deleteSpChatById(spChat1.getChatId());
//            }
//        }
//        return null;
//    }


}

